/*
 * @Author: zjj
 * @Date: 2018-06-10 14:35:50
 * @LastEditors: zjj
 * @LastEditTime: 2018-06-10 14:53:20
 * @Description: component（组建封装）
 */
import wepy from 'wepy'
import {
  reqUrl,
  reqHead,
  reqType,
  reqTip,
  reqGetCode
} from '../config'
/**
 * 轻提示，不带icon
 * @param {string} [title='这是一个轻提示！']
 * @param {number} [duration=3000]
 * @param {boolean} [mask=false]
 */
const toast = (title = '这是一个轻提示！', duration = 3000, mask = false) => (
  wepy.showToast({
    title,
    icon: 'none',
    duration,
    mask,
  })
);

/**
 * 带确认按钮弹框！
 * @param {string} [content='带确认按钮弹框！']
 * @param {string} [confirmColor='#3CC51F']
 */
const modal = (content = '带确认按钮弹框！', confirmColor = '#3CC51F') => (
  wepy.showModal({
    title: '',
    content,
    showCancel: false,
    confirmColor
  })
)

/**
 * 图片预览
 * @param {string} [current='']
 * @param {*} [urls=[]]
 */
const previewImage = (current = '', urls = []) => (
  wepy.previewImage({
    current, // 当前显示图片的http链接
    urls, // 需要预览的图片http链接列表
  })
)

/**
 * 获取微信code
 * @param {*} cb
 */
const getCode = cb => {
  wepy.login({
    success(res) {
      const code = res.code;
      if (code) {
        // 获取code成功回调
        cb && cb(code);
      } else {
        // 获取code失败重新获取
        getCode();
      }
    }
  });
}

/**
 * 服务器返回openid
 * @param {*} code
 * @param {*} cd
 */
const resGetcode = (code, cb) => {
  // 发起请求
  wepy.request({
    url: reqGetCode,
    data: {
      js_code: code
    },
    header: reqHead,
    method: reqType,
    dataType: reqType,
    // 请求成功
    success(res) {
      const {
        data
      } = res;
      const jsData = JSON.parse(data);
      const dataCon = jsData.data;
      if (dataCon.auth_code) {
        // 返回标示
        cb && cb(dataCon.auth_code)
      } else {
        // 没有标示重新获取;
        resGetcode();
      }
    },
    // 请求失败
    fail(err) {
      // 请求失败重新获取
      resGetcode();
    }
  });
}

/**
 * 请求封装
 * @param {*} cb
 */
const request = (url, data, cb) => {
  wepy.request({
    url: reqUrl + url,
    data,
    header: reqHead,
    method: reqType,
    dataType: reqType,
    // 请求成功
    success(res) {
      const {
        data
      } = res;
      const jsonData = JSON.parse(data);
      let access_token = jsonData['access-token'];
      let uid = jsonData['uid'];
      if (jsonData.code === 200) {
        cb && cb(access_token, uid);
      } else {  
        toast(jsonData.message)
      }
    },
    // 请求失败
    fail(err) {
      toast(err.message)
    }
  });
}

/**
 * 获取getAccessToken
 * @param {*} cb
 */
const getAccessToken = (cb) => {
  getCode(code => {
   wepy.showLoading({
      title: reqTip,
      mask: true
    });
    // 获取token
    wepy.request({
      url: reqGetCode,
      data: {
        js_code: code
      },
      header: reqHead,
      method: reqType,
      dataType: reqType,
      // 请求成功
      success(res) {
        const {data} = res;
        const jsonData = JSON.parse(data);
        const {auth_code, flag, uid} = jsonData.data;
        let access_token = jsonData.data['access-token'];
        // 判断是否有access_token存在
        if (access_token) {
          // 缓存access_token；
          wepy.setStorageSync('access_token', access_token);
          wepy.setStorageSync('uid', uid);
          wepy.setStorageSync('flag', flag);
          // if (flag) {
          //   // setTimeout(() => wepy.redirectTo({url: `/pages/my-grounp`}), 300)
          // };
          // 回调
          cb && cb();
        }else {
          setTimeout(() => {
            wepy.navigateTo({url: `/pages/author?auth_code=${auth_code}`});
          }, 300);
        }
      },
      // 请求失败
      fail(err) {
          toast(err.message)
      },
      // 请求结束
      complete() {
        wepy.hideLoading();
      }
    });
  })
}

export {
  toast,
  modal,
  previewImage,
  getCode,
  getAccessToken,
  request
}